package com.example.dllo.moondog.tools;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;

import com.android.volley.toolbox.ImageLoader;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by dllo on 16/1/18.
 */
public class DiskCache implements ImageLoader.ImageCache {
    private String cacheDir = "";

    public DiskCache() {
        //判断外置SD卡是否处于挂载的状态
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            //获取根路径
            File root = Environment.getExternalStorageDirectory();
            File cacheFile = new File(root.getAbsolutePath() + "/cacheKeep");
            //如果该文件夹不存在，创建
            if (!cacheFile.exists()) {
                cacheFile.mkdir();
            }
            cacheDir = cacheFile.getAbsolutePath(); //缓存路径
        }
    }

    @Override
    public Bitmap getBitmap(String url) {
//        url = url.substring(url.lastIndexOf("/"), url.lastIndexOf(".") + 4);
        //路径下的文件名
//        return BitmapFactory.decodeFile(cacheDir + "/" + url);
        url = MD5Util.getMD5Str(url);
        return BitmapFactory.decodeFile(cacheDir + url + ".jpg");

    }

    @Override
    public void putBitmap(String url, Bitmap bitmap) {
//        url = url.substring(url.lastIndexOf("/"), url.lastIndexOf(".") + 4);
//        FileOutputStream fos = null;
//        try {
//            fos = new FileOutputStream(cacheDir + "/" + url);
//            String path = cacheDir + "/" + url;
//            Log.d("DiskCache", path);
//            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        } finally {
//            if (null != fos) {
//                try {
//                    fos.close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//        }

        File file = new File(cacheDir);
        if (!file.exists()) {
            file.mkdir();
        }
        url = MD5Util.getMD5Str(url);
        File imageFile = new File(cacheDir, url+".jpg");
        if (!imageFile.exists()) {
            FileOutputStream fileOutputStream = null;
            try {
                imageFile.createNewFile();
                fileOutputStream = new FileOutputStream(imageFile);
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (null != fileOutputStream) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            }
        }

    }
}
